package com.dzsw.config;

import com.dzsw.filter.CustomLoginFilter;
import com.dzsw.security.MyAuthProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SpringSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity, CustomLoginFilter customLoginFilter) throws Exception {
        httpSecurity.addFilterBefore(customLoginFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity.sessionManagement(smg -> {
           smg.maximumSessions(1);
        });
        return httpSecurity.build();
    }

    @Bean
    public CustomLoginFilter customLoginFilter(AuthenticationConfiguration authConfig) throws Exception {
        return new CustomLoginFilter(authConfig.getAuthenticationManager());
    }

    @Bean
    public MyAuthProvider myAuthProvider() {
        return new MyAuthProvider();
    }
}
